#include "epoll_monitor.h"
#include "common.h"
#include <unistd.h>
#include <errno.h>

epoll_monitor::epoll_monitor() : epfd(-1) {
}

epoll_monitor::~epoll_monitor(){
	release();
}

int epoll_monitor::init(){

	int ret = 0;

	if (is_inited()){

	}else{
		epfd = epoll_create(EPOLL_SIZE);
		if (epfd < 0){
			ret = -1;
		}
	}

	LOGI("epoll_create %d.", ret);
	return ret;
}

bool epoll_monitor::is_inited(){
	return (epfd > 0);
}

void epoll_monitor::release(){
	if (is_inited()){
		close(epfd);
		epfd = -1;
	}
}

int epoll_monitor::wait(int timeout){
	// timeout==-1为阻塞
	return epoll_wait(epfd, events, EPOLL_SIZE, timeout);
}

int epoll_monitor::monitor_add(int fd, forward_event* ptr_fe, unsigned int epoll_events){

	epoll_event ev;
	ev.events = epoll_events;
	ev.data.ptr = ptr_fe;

	int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
	if (ret == -1){
		int err = errno;
		LOGE("monitor_add %d failed, role = %d, err = %d", fd, ptr_fe->role, err);
	}

	return ret;
}

int epoll_monitor::monitor_del(int fd){
	int ret = -1;
	if (epfd > 0){
		ret = epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL);
		int err = errno;
		LOGE("monitor_del %d failed, err = %d", fd, err);
	}
	return ret;
}
